package com.imooc.controller;

import com.imooc.common.converter.OrderForm2OrderDTOConverter;
import com.imooc.common.dto.OrderDTO;
import com.imooc.common.enums.ResultEnum;
import com.imooc.common.exception.SelllException;
import com.imooc.common.form.OrderForm;
import com.imooc.common.utils.ResultVoUtil;
import com.imooc.common.vo.ResultVo;
import com.imooc.service.BuyerSercice;
import com.imooc.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/buyer/order")
public class BuyerOrderController {

    @Autowired
    BuyerSercice buyerSercice;

    @Autowired
    OrderService orderService;

    // 创建订单
    @PostMapping("/create")
    public ResultVo<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new SelllException(ResultEnum.PARAM_ERROR, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        log.info("[下单] orderDTO：{}",orderDTO);
        OrderDTO orderDTO1 = orderService.create(orderDTO);

        Map<String, String> hashMap = new HashMap();
        hashMap.put("orderId", orderDTO1.getOrderId());

        return ResultVoUtil.success(hashMap);
    }


    // 订单列表
    @GetMapping("/list")
    public ResultVo<List<OrderDTO>> list(@RequestParam("openid") String openid,
                                         @RequestParam(value = "page", defaultValue = "0") Integer page,
                                         @RequestParam(value = "size", defaultValue = "10") Integer size) {
        if (StringUtils.isBlank(openid)) {
            throw new SelllException(ResultEnum.PARAM_ERROR, "openid不能为空");
        }

        PageRequest request = PageRequest.of(page, size);
        Page<OrderDTO> orderDTOPage = orderService.findByBuyerOpenid(openid, request);
        return ResultVoUtil.success(orderDTOPage.getContent());
    }

    // 订单详情
    @GetMapping("/detail")
    public ResultVo<List<OrderDTO>> detail(@RequestParam("openid") String openid,
                                           @RequestParam("orderId") String orderId) {
        OrderDTO orderDTO = buyerSercice.findOrderOne(orderId, openid);
        return ResultVoUtil.success(orderDTO);
    }

    // 取消订单
    @GetMapping("/cancel")
    public ResultVo cancel(@RequestParam("openid") String openid,
                           @RequestParam("orderId") String orderId) {
        buyerSercice.cancel(orderId, openid);
        return ResultVoUtil.success();
    }
}
